/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.primefaces.context.RequestContext;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import src.HibernateUtil;
import src.Menu;
import src.domain.security.Policy;
import src.domain.security.Ugpolicy;
import src.domain.security.UgpolicyId;
import src.domain.security.Ugroup;
import src.services.MenuModel;
import src.services.security.UgpolicyModel;
import src.util.Constanta;
import src.util.Messager;

/**
 *
 * @author Yusup Jauhari Shandi <in.visi>
 */
@ManagedBean
@SessionScoped
public class UgpolicyBean implements Serializable{
    private TreeNode rootNode;
    private List<Menu> menuAll;
    private List<Policy> policys;  
    private List<Ugpolicy> listToSave;
    private Ugroup selectedGroup;
    
    public UgpolicyBean() {
      //  rootNode = new DefaultTreeNode("root", null);
        initForm();
    }
    
    final public void initForm(){
       // src.services.MenuModel menuModel = new src.services.MenuModel();
     //   menuAll = menuModel.findAll(null);
        //generateTreeNode(null,rootNode);
    }

    public Ugroup getSelectedGroup() {
        return selectedGroup;
    }

    public void setSelectedGroup(Ugroup selectedGroup) {
        this.selectedGroup = selectedGroup;
    }
    
    private void generateTreeNode(Integer parentId, TreeNode parent){
        Map<String, Object> filters = new HashMap<>();       
        filters.put("parentId", parentId);
        filters.put("hide", 0);
        filters.put("disabled", 0);
        MenuModel helper = new MenuModel();
        List<Menu> data = helper.findAll(filters);;
        //this.glaccnts = helper.findAll(filters);
        if (data.isEmpty()){
            return;
        }
        else {
            for (int i=0;i<data.size();i++){
                Menu menu = data.get(i);
                //if (gl.getParentGlaccntId()==null){
                    TreeNode x = new DefaultTreeNode(menu, parent);
                    String allow = this.cekAccess(this.selectedGroup.getUgroupId(), menu.getMenuId());
                    if (allow==null){
                        allow = "";
                    } else {
                        menu.getGroupPolicyAction().setCanAdd(allow.indexOf(Constanta.POLICY_INSERT)>-1);
                        menu.getGroupPolicyAction().setCanApprove(allow.indexOf(Constanta.POLICY_APPROVAL)>-1);
                        menu.getGroupPolicyAction().setCanDelete(allow.indexOf(Constanta.POLICY_DELETE)>-1);
                        menu.getGroupPolicyAction().setCanEdit(allow.indexOf(Constanta.POLICY_UPDATE)>-1);
                        menu.getGroupPolicyAction().setCanOpen(allow.indexOf(Constanta.POLICY_OPEN)>-1);
                        menu.getGroupPolicyAction().setCanPrint(allow.indexOf(Constanta.POLICY_PRINT)>-1);
                        //menu.getGroupPolicyAction().setCanUnApprove(allow.indexOf(Constanta.POLICY_)>-1);
                    }
                    generateTreeNode(menu.getMenuId(),x);
                ////}
            }
            
                      
        }
    }
    
    
    private void generateTreeNodeOld(int Start,TreeNode parent){
        if (Start>=menuAll.size()){
            return;
        }
        else {
            Menu menu = menuAll.get(Start);
            if (menu.getParentId()==null){
                TreeNode x = new DefaultTreeNode(menu, rootNode);
                parent = x;
                Start++;
                generateTreeNode(Start,parent);
            }
            else if (menu.getMenuType().equals("SUBMENU")){
                TreeNode x = new DefaultTreeNode(menu, parent);                    
                parent = x;
                Start++;
                generateTreeNode(Start,parent);
            }          
            else {
                Start++;
                TreeNode x = new DefaultTreeNode(menu, parent);     
                generateTreeNode(Start,parent);
            }
        }
            
    }
    
    public void onRowSelect(SelectEvent event){
       // FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Selected", event.toString());
        //  increment();
     //   FacesContext.getCurrentInstance().addMessage(null, msg);
        rootNode = new DefaultTreeNode("root",null);
        generateTreeNode(null, rootNode);
         //Messager.showSaveUpdateStatus(success);        
        //context.addCallbackParam("success", success);
    }
    
     public void onNodeSelect(NodeSelectEvent event) {
        // FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Selected", event.getTreeNode().getData().toString());
        //  increment();
        //FacesContext.getCurrentInstance().addMessage(null, msg);

        Menu x = (Menu)event.getTreeNode().getData();
         if (((x.getUrl()!=null)||(!x.getUrl().equals("")))){
             //showTabs.add(menuAll.get(menuAll.indexOf(x)));
             //tabActiveIndex = showTabs.size()-1;
        }

    }
     
     
    public String cekAccess(Integer groupId, Integer menuId){
        String rs;
        UgpolicyModel helper = new UgpolicyModel();   
        rs = helper.getAllowAction(menuId, groupId);
        return rs;
    } 
    
    public boolean cekButtonAccess(Integer menuId,String buttonType){
        boolean rs;
        UgpolicyModel helper = new UgpolicyModel();   
         FacesContext fc = FacesContext.getCurrentInstance();
        //Session session = (Session) fc.getExternalContext().getSession(false);
        HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
        Integer groupId = (Integer) session.getAttribute("groupid");
        rs = (helper.getAllowAction(menuId, groupId).indexOf(buttonType)>-1);
        return rs;
    }
     
    private TreeNode getCurrentNode(Integer menuId,TreeNode parent){
        TreeNode rs = null;
        if (parent==null)
                    parent = rootNode;
                for(int j=0;j<parent.getChildCount();j++){
                     TreeNode z = parent.getChildren().get(j);  
                     Menu menu2 = (Menu)z.getData();
                     if (menu2.getMenuId().equals(menuId)){
                        rs = z;
                        
                        break;
                    }
                }
        return rs;        
    }

    public TreeNode getRootNode() {
        return rootNode;
    }
    
    private void saveAllNew(TreeNode current){
        Menu menu = null;
        Ugpolicy data = new Ugpolicy();
        UgpolicyModel helper = new UgpolicyModel();   
        if (current.getData().toString().equals("root")){
            return;
        }
        else if (current.getChildCount()>=0){
            menu = (Menu) current.getData();
            UgpolicyId id = new UgpolicyId(this.selectedGroup.getUgroupId(), menu.getMenuId().intValue());
            data.setId(id);
            StringBuilder allow= new StringBuilder();
            if (menu.getPolicyAction().isCanAdd()) allow.append(Constanta.POLICY_INSERT);// else allow.append("0");
            if (menu.getPolicyAction().isCanEdit()) allow.append(Constanta.POLICY_UPDATE);// else allow.append("0");
            if (menu.getPolicyAction().isCanDelete()) allow.append(Constanta.POLICY_DELETE); //else allow.append("0");
            if (menu.getPolicyAction().isCanPrint()) allow.append(Constanta.POLICY_PRINT); //else allow.append("0");
            if (menu.getPolicyAction().isCanApprove()) allow.append(Constanta.POLICY_APPROVAL); //else allow.append("0");
            if (menu.getPolicyAction().isCanOpen()) allow.append(Constanta.POLICY_OPEN); //else allow.append("0");
            data.setAllowedActions(allow.toString());
            helper.saveData(data);
            if (current.getChildCount()>0){
                saveAllNew(current);
            }
        }
        
    }
    
    private void saveAll(int count,TreeNode current){
       // if (count < 0){
         //   return;
        //}
        
        
        Ugpolicy data = new Ugpolicy();
        UgpolicyModel helper = new UgpolicyModel();   
        Menu menu = null;
        //if (current.getChildCount()>0){
        if ((count>0)&&(current.getChildCount()>0)){
            current = current.getChildren().get(count-1);
            menu = (Menu) current.getData();
            if (current.getChildCount()>0){
                count = current.getChildCount();
                if (count>0)
                saveAll(count, current);
            }
            else {
                count--;
               current = current.getParent();
            }
            
        }
        else if (count>0){
           
            //.getChildren().get(count).getData();
            current = current.getParent().getChildren().get(count-1);
            menu = (Menu) current.getData();
             count--;
        }
        else {
           if (current.getData().toString().equals("root")) {
               count--;
               return;
           }
            menu = (Menu) current.getData();            
           
            
            count = current.getParent().getChildren().indexOf(current);
            
            current = current.getParent();
        }
        UgpolicyId id = new UgpolicyId(this.selectedGroup.getUgroupId(), menu.getMenuId().intValue());
        data.setId(id);
        StringBuilder allow= new StringBuilder();
        if (menu.getPolicyAction().isCanAdd()) allow.append(Constanta.POLICY_INSERT);// else allow.append("0");
        if (menu.getPolicyAction().isCanEdit()) allow.append(Constanta.POLICY_UPDATE);// else allow.append("0");
        if (menu.getPolicyAction().isCanDelete()) allow.append(Constanta.POLICY_DELETE); //else allow.append("0");
        if (menu.getPolicyAction().isCanPrint()) allow.append(Constanta.POLICY_PRINT); //else allow.append("0");
        if (menu.getPolicyAction().isCanApprove()) allow.append(Constanta.POLICY_APPROVAL); //else allow.append("0");
        if (menu.getPolicyAction().isCanOpen()) allow.append(Constanta.POLICY_OPEN); //else allow.append("0");
        data.setAllowedActions(allow.toString());
        helper.saveData(data);
        
        if (current.getChildCount()>0)
       // if (count>=0)
            saveAll(count, current);
    
    }
    
    public void convertTreeNode(TreeNode parent){
        //List<Ugpolicy> rs = null;
        //return rs;
        if (parent.getChildCount()==0){
            Ugpolicy ug = new Ugpolicy();
            Menu menu = (Menu) parent.getData();
            UgpolicyId id = new UgpolicyId(this.selectedGroup.getUgroupId(), menu.getMenuId().intValue());
            ug.setId(id);
            StringBuilder allow= new StringBuilder();
            if (menu.getGroupPolicyAction().isCanAdd()) allow.append(Constanta.POLICY_INSERT);// else allow.append("0");
            if (menu.getGroupPolicyAction().isCanEdit()) allow.append(Constanta.POLICY_UPDATE);// else allow.append("0");
            if (menu.getGroupPolicyAction().isCanDelete()) allow.append(Constanta.POLICY_DELETE); //else allow.append("0");
            if (menu.getGroupPolicyAction().isCanPrint()) allow.append(Constanta.POLICY_PRINT); //else allow.append("0");
            if (menu.getGroupPolicyAction().isCanApprove()) allow.append(Constanta.POLICY_APPROVAL); //else allow.append("0");
            if (menu.getGroupPolicyAction().isCanOpen()) allow.append(Constanta.POLICY_OPEN); //else allow.append("0");
            ug.setAllowedActions(allow.toString());
                   
            listToSave.add(ug);
            return;
        }
        else {
            for (int i=0;i<parent.getChildCount();i++){
                
                convertTreeNode(parent.getChildren().get(i));
            }
        }
    }
    

    
    public void save() {
        listToSave = new ArrayList<>();
        convertTreeNode(rootNode);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        org.hibernate.Transaction tx = session.beginTransaction();
        boolean success;
        
        try {
            
            List<Ugpolicy> trxs = new  ArrayList<>();
            
        //    Query q = session.createQuery("delete from ugpolicy where");
          //  q.executeUpdate();
            
            for (int i=0; i< listToSave.size(); i++) {
                        Ugpolicy trx = (Ugpolicy) listToSave.get(i);                        
                        session.saveOrUpdate(trx);
                        trxs.add(trx);
            }
                
            
            
                     
            tx.commit();
            success = true;  
            
        } catch (RuntimeException e) {
            
            if (tx != null && tx.isActive()) {
                try {
                    tx.rollback();
                } catch (HibernateException e1) {}

                throw e;
            }
            success = false;  
        }

        //return success;
        Messager.showSaveUpdateStatus(success);        
        RequestContext context = RequestContext.getCurrentInstance();
        context.addCallbackParam("success", success);  
    }
    
    public void saveOld(){
        RequestContext context = RequestContext.getCurrentInstance();
        boolean success=false;  
        convertTreeNode(rootNode);
        
       // saveAllNew(rootNode);
             //saveAll(rootNode.getChildCount(), rootNode);
        /*Ugpolicy data = new Ugpolicy();
        UgpolicyModel helper = new UgpolicyModel();        
        
        for (int i=0;i<rootNode.getChildCount();i++)        {
            Menu menu = (Menu) rootNode.getChildren().get(i).getData();
            UgpolicyId id = new UgpolicyId(this.selectedGroup.getUgroupId(), menu.getMenuId().intValue());
            data.setId(id);
            StringBuffer allow= new StringBuffer();
            if (menu.getPolicyAction().isCanAdd()) allow.append("1"); else allow.append("0");
            if (menu.getPolicyAction().isCanEdit()) allow.append("1"); else allow.append("0");
            if (menu.getPolicyAction().isCanDelete()) allow.append("1"); else allow.append("0");
            if (menu.getPolicyAction().isCanPrint()) allow.append("1"); else allow.append("0");
            if (menu.getPolicyAction().isCanApprove()) allow.append("1"); else allow.append("0");
            data.setAllowedActions(allow.toString());
            success = helper.saveData(data);
            if (!success) break;
        }
        * 
        */
        //data.setSavprodrates(productDetails);
        
        
        
        
        Messager.showSaveUpdateStatus(success);        
        context.addCallbackParam("success", success);  
    }
    
    
}
